package com.soft.base.protocol;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class ResultT<T> implements Serializable {
    @Setter
    @Getter
    int code;
    @Getter
    @Setter
    String msg;
    @Getter
    @Setter
    T data = null;

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return code == ResponseCodes.SUCCESS;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isFail() {
        return code != ResponseCodes.SUCCESS;
    }

    public static <T> ResultT<T> error(String msg) {
        return build(ResponseCodes.DEFAULT_ERROR, msg);
    }

    public static <T> ResultT<T> success(String msg) {
        return build(ResponseCodes.SUCCESS, msg);
    }

    public static <T> ResultT<T> successData(T data) {
        return build(ResponseCodes.SUCCESS, "ok", data);
    }

    public static ResultT<Map> successMap(Object... params) {
        ResultT<Map> result = build(ResponseCodes.SUCCESS, "ok", Map.class);
        result.setData(new HashMap<>(1));
        int size = 2;
        for (int i = 0; i < params.length; i += size) {
            result.getData().put(params[i], params[i + 1]);
        }
        return result;
    }

    public static <T> ResultT<T> success() {
        return build(ResponseCodes.SUCCESS, "ok");
    }

    public static <T> ResultT<T> permitDenied() {
        return build(ResponseCodes.PERMIT_DENIED, "permit denied");
    }

    public static <T> ResultT<T> build(int code, String msg) {
        ResultT<T> result = new ResultT<>();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(null);
        return result;
    }

    public static <T> ResultT<T> build(int code, String msg, Class<T> cls) {
        ResultT<T> result = new ResultT<T>();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(null);
        return result;
    }

    public static <T> ResultT<T> build(int code, String msg, T data) {
        ResultT<T> result = new ResultT<>();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

}
